package com.erp.erp_servers.Purchase.imp;

import com.erp.erp_dao.Purchase.IPurchaseDAO;
import com.erp.erp_dao.Purchase.IPurchaseFileDAO;
import com.erp.erp_dao.Purchase.IPurchaseLogDAO;
import com.erp.erp_dao.Purchase.IPurchaseProductDAO;
import com.erp.erp_entitys.Customer2.Customer2Entity;
import com.erp.erp_entitys.Purchase.*;
import com.erp.erp_entitys.Purchase.req.PurchaseOrderRestockReq;
import com.erp.erp_entitys.Purchase.req.PurchaseProductIntegrationReq;
import com.erp.erp_entitys.Purchase.req.purchaseSampleStatisticsReq;
import com.erp.erp_entitys.Purchase.res.PurchaseDataVo;
import com.erp.erp_entitys.Purchase.res.PurchaseOrderRestockRes;
import com.erp.erp_entitys.Purchase.res.PurchaseProductIntegrationRes;
import com.erp.erp_entitys.Purchase.res.purchaseSampleStatisticsRes;
import com.erp.erp_servers.Purchase.IPurchaseService;
import com.erp.utils.StringUtil;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional
public class ImpPurchaseService implements IPurchaseService {

    private SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Autowired
    private IPurchaseDAO purchaseDAO;
    @Autowired
    private IPurchaseProductDAO purchaseProductDAO;
    @Autowired
    private IPurchaseFileDAO purchaseFileDAO;
    @Autowired
    private IPurchaseLogDAO purchaseLogDAO;

    @Override
    public List<Purchase> queryAll(Purchase req) {
        return purchaseDAO.queryAll(req);
    }

    @Override
    public int deleteByPrimaryKey(Integer id, Integer upType, String upUser) {
        int num = 0;
        List<PurchaseProduct> dbProductList = purchaseProductDAO.selectProductByPuId(id);
        if (!CollectionUtils.isEmpty(dbProductList)){
            if(!CollectionUtils.isEmpty(dbProductList)){
                for (PurchaseProduct dbProduct : dbProductList){
                    dbProduct.setUpType(upType);
                    dbProduct.setUpUser(upUser);
                    Date now = new Date(System.currentTimeMillis());
                    try {
                        now = df.parse(df.format(now));
                    } catch (ParseException e) {
                        System.out.println("日期转化异常");
                        e.printStackTrace();
                    }
                    dbProduct.setUpTime(now);
                    dbProduct.setProValid(0);
                    int n = purchaseProductDAO.updateProValidByKey(dbProduct);
                    String upContext = "销售合同号："+dbProduct.getSalesContractNo()+" 产品编码："+dbProduct.getProductNo()+" 规格编码："+dbProduct.getSpecNo();
                    PurchaseLog purchaseLog = new PurchaseLog(id, upType, 2, upUser, now, upContext);
                    int logNum = purchaseLogDAO.insert(purchaseLog);
                }
//                int upNum = purchaseProductDAO.updateProValidByProList(dbProductList);
            }
//            List<Integer> idList = new ArrayList<Integer>();
//            for (PurchaseProduct dbProduct : dbProductList){
//                idList.add(dbProduct.getId());
//            }
//            if (idList.size()>0){
//                purchaseProductDAO.deleteByIdList(idList);
//            }
        }
        int backProNum = 0;
        if (!CollectionUtils.isEmpty(dbProductList)){
            for (PurchaseProduct pro : dbProductList){
                BigDecimal amount = pro.getAmount();
                if(amount.compareTo(BigDecimal.ZERO)>0){
                    Map<String,Object> map = new HashMap<>();
                    map.put("quantityUsed",amount);//回退数量
                    map.put("productId",pro.getProductId());//外销产品id
                    map.put("productNo",pro.getProductNo());//产品编码
                    map.put("specNo",pro.getSpecNo());//规格编码
//                    backProNum = purchaseProductDAO.backExportProductNum(map);
                }
            }
        }
        List<PurchaseFile> dbFileList = purchaseFileDAO.selectFileByPuId(id);
        if (!CollectionUtils.isEmpty(dbFileList)){
            List<Integer> idList = new ArrayList<Integer>();
            for (PurchaseFile dbFile : dbFileList){
                idList.add(dbFile.getId());
            }
            if (idList.size()>0){
                purchaseFileDAO.deleteByIdList(idList);
            }
        }
        List<PurchaseProduct> dbProductListNew = purchaseProductDAO.selectProductByPuId(id);
        if(dbProductListNew.isEmpty() || backProNum>0){
           num = updateValid(id, 0, upType, upUser);
//            num = purchaseDAO.deleteByPrimaryKey(id);
        }
        return num;
    }

    @Override
    public int insert(Purchase record) {
        if(record==null){return 0;}
        int num = 0;
        num = purchaseDAO.insert(record);
        if (num>0){
            List<PurchaseProduct> productList = record.getProductList();
            if (!CollectionUtils.isEmpty(productList)){
                for (PurchaseProduct pro : productList){
                    pro.setId(null);
                    pro.setPurchaseId(record.getId());
                    pro.setProValid(1);
                    pro.setUpType(record.getUpType());
                    pro.setUpUser(record.getUpUser());
                    Date now = record.getUpTime();
                    try {
                        now = df.parse(df.format(now));
                    } catch (ParseException e) {
                        now = new Date(System.currentTimeMillis());
                    }
                    pro.setUpTime(now);
                    int insertNum = purchaseProductDAO.insert(pro);
                    String upContext = "销售合同号："+pro.getSalesContractNo()+" 产品编码："+pro.getProductNo()+" 规格编码："+pro.getSpecNo();
                    PurchaseLog purchaseLog = new PurchaseLog(record.getId(), record.getUpType(), 2, record.getUpUser(), now, upContext);
                    int logNum = purchaseLogDAO.insert(purchaseLog);
                    if(insertNum>0){
                        Map<String,Object> map = new HashMap<>();
                        map.put("quantityUsed",pro.getAmount());//已用数量
                        map.put("productId",pro.getProductId());//外销产品id
                        map.put("productNo",pro.getProductNo());//产品编码
                        map.put("specNo",pro.getSpecNo());//规格编码
//                        int upProNum = purchaseProductDAO.upExportProductNum(map);
                    }
                }
            }

            List<PurchaseFile> fileList = record.getFileList();
            if (!CollectionUtils.isEmpty(fileList)){
                for (PurchaseFile file : fileList){
                    file.setPurchaseId(record.getId());
                    file.setFileExecutor(record.getExecutorCode());
                    String fileName = file.getFileName();
                    if(!StringUtils.isEmpty(fileName)){
                        if (StringUtils.isEmpty(file.getFileType())){
                            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                            file.setFileType(suffix);
                        }
                    }
                    file.setFileUploadTime(new Date(System.currentTimeMillis()));
                    purchaseFileDAO.insert(file);
                }
            }
        }
        return num;
    }

    @Override
    public int insertSelective(Purchase record) {
        return purchaseDAO.insertSelective(record);
    }

    @Override
    public Purchase selectByPrimaryKey(Integer id) {
        return purchaseDAO.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(Purchase record) {
        return purchaseDAO.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(Purchase record) {
        if (record==null || null == record.getId() || "".equals(record.getId())){
            return 0;
        }
        int num = purchaseDAO.updateByPrimaryKey(record);
        Date upTime = record.getUpTime();
        try {
            upTime = df.parse(df.format(upTime));
        } catch (ParseException e) {
            upTime = new Date(System.currentTimeMillis());
        }
        if(num>0){
            List<PurchaseProduct> productList = record.getProductList();
            List<PurchaseProduct> dbProductList = purchaseProductDAO.selectProductByPuId(record.getId());
            if (!CollectionUtils.isEmpty(dbProductList)){
                List<Integer> idList = new ArrayList<Integer>();
                if(!CollectionUtils.isEmpty(dbProductList)){
                    for (PurchaseProduct dbProduct : dbProductList){
                        dbProduct.setUpType(2);
                        dbProduct.setUpUser(record.getUpUser());
                        dbProduct.setUpTime(upTime);
                        dbProduct.setProValid(0);
                        int n = purchaseProductDAO.updateProValidByKey(dbProduct);
                        String upContext = "销售合同号："+dbProduct.getSalesContractNo()+" 产品编码："+dbProduct.getProductNo()+" 规格编码："+dbProduct.getSpecNo();
                        PurchaseLog purchaseLog = new PurchaseLog(record.getId(), 2, 2, record.getUpUser(), upTime, upContext);
                        int logNum = purchaseLogDAO.insert(purchaseLog);
                    }
//                    int upNum = purchaseProductDAO.updateProValidByProList(dbProductList);
                }
//                for (PurchaseProduct dbProduct : dbProductList){
//                    idList.add(dbProduct.getId());
//                }
//                if (idList.size()>0){
//                    purchaseProductDAO.deleteByIdList(idList);
//                }
            }
            if (!CollectionUtils.isEmpty(productList)){
                int backProNum = 0;
                if (!CollectionUtils.isEmpty(dbProductList)){
                    for (PurchaseProduct pro : dbProductList){
                        BigDecimal amount = pro.getAmount();
                        if(amount.compareTo(BigDecimal.ZERO)>0){
                            Map<String,Object> map = new HashMap<>();
                            map.put("quantityUsed",amount);//回退数量
                            map.put("productId",pro.getProductId());//外销产品id
                            map.put("productNo",pro.getProductNo());//产品编码
                            map.put("specNo",pro.getSpecNo());//规格编码
//                            backProNum = purchaseProductDAO.backExportProductNum(map);
                        }
                    }
                }
                if(backProNum >= 0 ){
                    for (PurchaseProduct pro : productList){
                        pro.setId(null);
                        pro.setPurchaseId(record.getId());
                        pro.setProValid(1);
                        pro.setUpType(1);
                        pro.setUpUser(record.getUpUser());
                        pro.setUpTime(upTime);
                        int insertNum = purchaseProductDAO.insert(pro);
                        String upContext = "销售合同号："+pro.getSalesContractNo()+" 产品编码："+pro.getProductNo()+" 规格编码："+pro.getSpecNo();
                        PurchaseLog purchaseLog = new PurchaseLog(record.getId(), 1, 2, record.getUpUser(), upTime, upContext);
                        int logNum = purchaseLogDAO.insert(purchaseLog);
//                        if(insertNum>0){
//                            Map<String,Object> map = new HashMap<>();
//                            map.put("quantityUsed",pro.getAmount());//已用数量
////                            map.put("salesContractNo",pro.getSalesContractNo());//外销合同号
//                            map.put("productId",pro.getProductId());//外销产品id
//                            map.put("productNo",pro.getProductNo());//产品编码
//                            map.put("specNo",pro.getSpecNo());//规格编码
////                            int upProNum = purchaseProductDAO.upExportProductNum(map);
//                        }
                    }
                }
            }
            List<PurchaseFile> fileList = record.getFileList();
            List<PurchaseFile> dbFileList = purchaseFileDAO.selectFileByPuId(record.getId());
            if (!CollectionUtils.isEmpty(dbFileList)){
                List<Integer> idList = new ArrayList<Integer>();
                for (PurchaseFile dbFile : dbFileList){
                    idList.add(dbFile.getId());
                }
                if (idList.size()>0){
                    purchaseFileDAO.deleteByIdList(idList);
                }
            }
            if (!CollectionUtils.isEmpty(fileList)){
                for (PurchaseFile file : fileList){
                    file.setPurchaseId(record.getId());
                    file.setFileExecutor(record.getExecutorCode());
                    String fileName = file.getFileName();
                    if(!StringUtils.isEmpty(fileName)){
                        if (StringUtils.isEmpty(file.getFileType())){
                            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                            file.setFileType(suffix);
                        }
                    }
                    file.setFileUploadTime(new Date(System.currentTimeMillis()));
                    purchaseFileDAO.insert(file);
                }
            }
        }
        return num;
    }

    @Override
    public PageInfo<PurchaseDataVo> selectPurchaseList(PurchaseVo vo) {
        if(StringUtils.isEmpty(vo.getExecutor()) && StringUtils.isEmpty(vo.getDeptOperationCode()) && StringUtils.isEmpty(vo.getDeptSalesmanCode()) && StringUtils.isEmpty(vo.getSalesman())){
            PageInfo pageInfo = new PageInfo();
            List<PurchaseDataVo> voList = new ArrayList<>();
            pageInfo.setList(voList);
            return pageInfo;
        }
        List<PurchaseDataVo> list = purchaseDAO.selectPurchasePageList(vo);
        if(!CollectionUtils.isEmpty(list)){
            List<String> idList = new ArrayList<>();
            for(PurchaseDataVo p : list){
                idList.add(p.getPurchaseOrderNo());
            }
            if(!CollectionUtils.isEmpty(idList)){
                List<PurchaseProcessEntity> processList = purchaseDAO.getProcessListInfo(idList);
                for (int i = 0; i < list.size(); i++) {
                    PurchaseDataVo purchase = list.get(i);
                    //采购总额
                    BigDecimal purchaseTotalPrice = new BigDecimal("0");
                    if(StringUtil.isNotEmpty(purchase.getPurchaseTotalPrice())){
                        purchaseTotalPrice = purchase.getPurchaseTotalPrice();
                    }
                    //采购总额RMB
                    BigDecimal purchaseTotalPriceRMB = new BigDecimal("0");
                    if("rmb-001".equals(purchase.getCurrency())){
                        purchaseTotalPriceRMB = purchaseTotalPrice;
                    }else {
                        purchaseTotalPriceRMB = purchaseTotalPrice.multiply(purchase.getUsdRate()).multiply(purchase.getRmbRate());
                    }
                    purchase.setPurchaseTotalPriceRMB(purchaseTotalPriceRMB.setScale(4, BigDecimal.ROUND_HALF_UP));
                    for (int j = 0; j < processList.size(); j++) {
                        PurchaseProcessEntity pp = processList.get(j);
                        if(purchase.getPurchaseOrderNo().equals(pp.getPurchaseNo())){
                            purchase.setBoxStatus(pp.getSTATUS());
                        }
                    }
                    list.set(i,purchase);
                }
            }
        }
        //获取分页信息
        PageInfo pageInfo = new PageInfo(list);
        if(CollectionUtils.isEmpty(list)){
            pageInfo.setList(null);
            return pageInfo;
        }
        pageInfo.setList(list);
        return pageInfo;
    }

    @Override
    public List<Purchase> selectByIdList(List<Integer> list) {
        return purchaseDAO.selectByIdList(list);
    }

    @Override
    public int updateBoxStatusByKey(PurchaseVo vo) {
        return purchaseDAO.updateBoxStatusByKey(vo);
    }

    @Override
    public int updateValid(Integer id, Integer valid, Integer upType, String upUser){
        Map<String,Object> map = new HashMap<>();
        map.put("id",id);
        map.put("valid",valid);
        map.put("upType",upType);
        map.put("upUser",upUser);
        map.put("upTime",new Date(System.currentTimeMillis()));
        return purchaseDAO.updateValid(map);
    }

    @Override
    public Purchase selectInfoById(Integer id) {
        return purchaseDAO.selectInfoById(id);
    }

    @Override
    public boolean isExist(String oddNumber) {
        List<Purchase> existList = purchaseDAO.isExist(oddNumber);
        return CollectionUtils.isEmpty(existList)?false:true;
    }

    @Override
    public Customer2Entity selectCustomer2ByCode(String code) {
        return purchaseDAO.selectCustomer2ByCode(code);
    }

    @Override
    public boolean updateStatus(String bid, String spStatus) {
        return purchaseDAO.updateStatus(bid,spStatus)==1?true:false;
    }

    @Override
    public Purchase selectByNo(String purchaseOrderNo) {
        PurchaseVo vo = new PurchaseVo();
        vo.setNumberLike(purchaseOrderNo);
        List<Purchase> list = purchaseDAO.selectPurchaseList(vo);
        Purchase purchase = null;
        if(!CollectionUtils.isEmpty(list)){
            purchase = list.get(0);
        }
        return purchase;
    }
    @Override
    public ImgUrl selectImgUrlById(Integer id){
        return purchaseDAO.selectImgUrlById(id);
    }

    @Override
    public List<PurchaseProduct> selectPurchaseProductByCode(String productNo, String specNo) {
        return purchaseProductDAO.selectPurchaseProductByCode(productNo, specNo);
    }

    @Override
    public int updatePurchaseFile(Integer id, String executorCode, List<PurchaseFile> fileList) {
        int num = 0;
        List<PurchaseFile> dbFileList = purchaseFileDAO.selectFileByPuId(id);
        if (!CollectionUtils.isEmpty(dbFileList)){
            List<Integer> idList = new ArrayList<Integer>();
            for (PurchaseFile dbFile : dbFileList){
                idList.add(dbFile.getId());
            }
            if (idList.size()>0){
                purchaseFileDAO.deleteByIdList(idList);
            }
        }
        if (!CollectionUtils.isEmpty(fileList)){
            for (PurchaseFile file : fileList){
                file.setPurchaseId(id);
                file.setFileExecutor(executorCode);
                String fileName = file.getFileName();
                if(!StringUtils.isEmpty(fileName)){
                    if (StringUtils.isEmpty(file.getFileType())){
                        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                        file.setFileType(suffix);
                    }
                }
                file.setFileUploadTime(new Date(System.currentTimeMillis()));
                num = purchaseFileDAO.insert(file);
            }
        }
        return num;
    }

    /**
     * 根据采购单号获取名称中包含fileName的信息的附件
     *
     * @param purchaseOrderNo
     * @param fileName
     * @return
     */
    @Override
    public  List<PurchaseFile> getFileByPurchaseOrderNo(String purchaseOrderNo, String fileName) {
        PurchaseFile pf=new PurchaseFile();
        pf.setFileName(fileName);
        //用此字段代替采购单号来进行查询
        pf.setWjName(purchaseOrderNo);
        List<PurchaseFile> fileByPurchaseOrderNo = purchaseFileDAO.getFileByPurchaseOrderNo(pf);
        return fileByPurchaseOrderNo;
    }

    /**
     * 保存采购审批信息
     *
     * @param purchaseProcessEntity
     * @return
     */
    @Override
    public int insertProcess(PurchaseProcessEntity purchaseProcessEntity) {
        int num=0;
        int processCount = purchaseDAO.getProcessCount(purchaseProcessEntity.getPurchaseNo());
        if(processCount == 0){
           num= purchaseDAO.insertProcess(purchaseProcessEntity);
        }else{
            num=purchaseDAO.updateProcess(purchaseProcessEntity);
        }
        return num;
    }

    /**
     * 根据采购订单号查询审批信息
     *
     * @param purchaseidList
     * @return
     */
    @Override
    public List<PurchaseProcessEntity> getProcessList(List purchaseidList) {
        return purchaseDAO.getProcessListInfo(purchaseidList);
    }

    /**
     * 查询审批人的审批信息
     *
     * @param spr
     * @return
     */
    @Override
    public List<PurchaseProcessEntity> getProcessBySPR(String spr) {
        return purchaseDAO.getProcessBySPR(spr);
    }

    @Override
    public List<PurchaseOrderRestockRes> purchaseOrderRestockList(PurchaseOrderRestockReq req) {
        return purchaseDAO.purchaseOrderRestockList(req);
    }

    @Override
    public List<PurchaseProductIntegrationRes> purchaseProductIntegrationList(PurchaseProductIntegrationReq req) {
        return purchaseDAO.purchaseProductIntegrationList(req);
    }

    /**
     * 获取采购信息
     * @param purchase 采购实体
     * @return 采购信息
     */
    @Override
    public Purchase getPurchaseInfo(Purchase purchase) {
        return purchaseDAO.getPurchaseInfo(purchase);
    }

    @Override
    public List<purchaseSampleStatisticsRes> purchaseSampleStatisticsList(purchaseSampleStatisticsReq req) {
        return purchaseDAO.purchaseSampleStatisticsList(req);
    }
}
